package com.example.choupaiapp.main.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.main.constant.Config;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ASUS on 2019/11/1.
 */

public class QQLoginUtil {
    public static Tencent mTencent;

    private static QQLoginUtil qqLoginUtil = null;

    private QQLoginUtil() {
        mTencent = Tencent.createInstance(Config.QQ_APP_ID, ContextUtil.getContext());
    }

    public static QQLoginUtil getInstance() {
        if (qqLoginUtil == null) {
            qqLoginUtil = new QQLoginUtil();
        }
        return qqLoginUtil;
    }

    public void qqLogin(Activity activity,IUiListener listener) {
        if (!mTencent.isSessionValid()) {
            mTencent.login(activity,"all",listener);
        }
    }

    public boolean isQQAppInstalled() {
        if (mTencent.isQQInstalled(ContextUtil.getContext())) {
            return true;
        } else {
            isAvilible(ContextUtil.getContext(), "com.tencent.mobileqq");
        }

        return false;
    }

    public boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

}
